require 'MVVM.Sources.View.Adaptor'

ToggleGroupAdaptor = class('ToggleGroupAdaptor', Adaptor)

function ToggleGroupAdaptor:ctor(gameObjectList, propertyName, _viewCallBack, binder,sound)
    sound = sound or 'SoundEffect/new_tab_click'
    binder:RegisterEvent(function(viewModel, property)
        for i = 1, #gameObjectList do
            local toggle = gameObjectList[i]:GetComponent('Toggle')
            toggle.onValueChanged:AddListener(function(isOn)
                if isOn then
                    property.Value = i
                end
            end)
        end
    end, function()
        for i = 1, #gameObjectList do
            local toggle = gameObjectList[i]:GetComponent('Toggle')
            toggle.onValueChanged:RemoveAllListeners()
        end
    end, propertyName)

    binder:Add(propertyName,function(oldValue,newValue)
        if newValue == nil or oldValue == newValue then
            return
        end

        if gameObjectList[oldValue] then
            local spine = gameObjectList[oldValue].transform:Find('Checked/Spine')
            if spine then
                spine.gameObject:SetActive(false)
            end
        end

        if gameObjectList[newValue] then
            gameObjectList[newValue]:GetComponent('Toggle').isOn = true
            local spine = gameObjectList[newValue].transform:Find('Checked/Spine')
            if spine then
                spine.gameObject:SetActive(true)
            end
            if _viewCallBack ~= nil then
                _viewCallBack(oldValue,newValue)
                if #sound > 0 and oldValue ~= nil then
                    AudioManager.PlaySound(sound)
                end
            end
        end
    end)
end